package com.huatai.paas.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huatai.common.api.R;
import com.huatai.common.config.MinioAPI;
import com.huatai.common.constant.MinioCommonBucket;
import com.huatai.paas.dto.*;
import com.huatai.paas.dto.info.QueryModelManagementInfo;
import com.huatai.paas.entity.FileListEntity;
import com.huatai.paas.mapper.ModelManagementMapper;
import com.huatai.paas.service.FileListService;
import com.huatai.paas.service.ModelManagementService;
import com.huatai.paas.service.ProjectManagementService;
import com.huatai.paas.websocket.StatusChangeWebsocketHandler;
import okhttp3.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * <b>ModelManagementServiceImpl</b>
 *
 * @description: ModelManagementServiceImpl <br>
 * @date: 2024/7/22 16:58 <br>
 * @author: lhm <br>
 * @version: 1.0 <br>
 */

@Service
public class ModelManagementServiceImpl extends ServiceImpl<ModelManagementMapper, ModelManagement> implements ModelManagementService {
	private static final Logger logger = LoggerFactory.getLogger(ModelManagementServiceImpl.class);

	@Autowired
	private FileListService fileListService;

	@Autowired
	private StatusChangeWebsocketHandler statusChangeWebsocketHandler;

	@Autowired
	@Lazy
	private ProjectManagementService projectManagementService;

	@Value("${minio.PREURL}")
	private String minioApi;

	@Value("${minio.PREURL-IP}")
	private String minioApiIp;

	@Value("${main.masterIp}")
	private String masterIp;

	@Value("${main.toolPort}")
	private String toolPort;

	@Value("${main.path}")
	private String path;

//	@Value("${main.ip}")
	private String ip = System.getenv("HOST_IP");

	@Value("${main.port}")
	private String port;


	@Override
	public IPage<QueryModelManagementInfo> queryModelManagementList(QueryModelManagementDto dto) {
		if (0 == dto.getPageNum()){
			dto.setPageNum(1);
		}
		if (0 == dto.getPageSize()){
			dto.setPageSize(10);
		}
		Page<QueryModelManagementInfo> page = new Page<>(dto.getPageNum(), dto.getPageSize());
		IPage<QueryModelManagementInfo> pageInfo = baseMapper.queryModelManagementList(page,dto);
		return pageInfo;
	}

	@Override
	public R createModelManagement(CreateModelManagementDto dto) {
		FileListEntity fileListEntity = fileListService.queryFileByMd5(dto.getFileId());
		if(fileListEntity == null){
			return R.fail("模型源文件信息异常");
		}
		ModelManagement modelManagement = new ModelManagement();
		modelManagement.setModelName(dto.getModelName());
		modelManagement.setImageUrl(dto.getImageUrl());
		modelManagement.setEnable("2");
		modelManagement.setCreateTime(new Date());
		modelManagement.setFileId(fileListEntity.getId().toString());
		modelManagement.setUpdateTime(new Date());
		baseMapper.insert(modelManagement);
		statusChangeWebsocketHandler.sendMessageToAllUser("新增模型",modelManagement);

		OkHttpClient client = new OkHttpClient();
		JSONObject paramData = new JSONObject();
		List<String> dataList = new LinkedList<>();
		dataList.add(minioApiIp+fileListEntity.getPath());
		paramData.put("list",dataList);
		paramData.put("callUrl","http://" + ip + ":" + port +"/ht-paas/transform/modelManagement?type=2&itemId="+modelManagement.getId()+"&status=");

		RequestBody body = RequestBody.create(MediaType.parse("application/json"), paramData.toJSONString());
		String requestUrl = masterIp + ":" + toolPort + path;
		// 创建 HTTP 请求
		Request request = new Request.Builder()
			.url(requestUrl)
			.post(body)
			.build();
		// 发送异步请求
		client.newCall(request).enqueue(new Callback() {
			@Override
			public void onFailure(Call call, IOException e) {
				log.error("模型转换服务器异常："+e.getMessage());
				modelManagement.setEnable("3");
				baseMapper.updateById(modelManagement);
			}
			@Override
			public void onResponse(Call call, Response response) throws IOException {
			}
		});
		return R.data(modelManagement.getId());
	}

	@Override
	public boolean deleteModelManagementById(Long id) {
		UpdateWrapper updateWrapper = new UpdateWrapper();
		updateWrapper.eq("id",id);
		updateWrapper.set("enable","0");
		int update = baseMapper.update(null, updateWrapper);
		if (1 == update){
			return true;
		}
		return false;
	}

	@Override
	public List<ModelManagement> queryModelListById(List<Long> modelIdList) {
		return baseMapper.queryModelListById(modelIdList);
	}

	@Override
	public R transformModelManagement(Integer type, Long itemId,Integer status) {
		if(status.intValue() == 0){
			status = 3;
		}
		if(type.intValue() == 1){
			ProjectManagement projectManagement = projectManagementService.getProjectById(itemId);
			if(projectManagement == null){
				return R.fail("项目信息异常");
			}
			projectManagement.setEnable(status.toString());
			projectManagementService.updateProject(projectManagement);
		}else{
			ModelManagement modelManagement = baseMapper.selectById(itemId);
			if(modelManagement == null){
				return R.fail("模型信息异常");
			}
			modelManagement.setEnable(status.toString());
			baseMapper.updateById(modelManagement);
		}

		if(type.intValue() == 1){
			statusChangeWebsocketHandler.sendMessageToAllUser("地形信息",projectManagementService.getProjectById(itemId));
		}else{
			statusChangeWebsocketHandler.sendMessageToAllUser("模型信息",baseMapper.selectById(itemId));
		}
		return R.success("绑定成功");
	}

	@Override
	public R modelManagementDetail(Long modelId) {
		return R.data(baseMapper.modelManagementDetail(modelId));
	}
}
